<template>
  <div id="app">
    <div class="container">
      <HeaderSection />
      
      <div class="content">
        <div class="toolbar">
          <button class="config-btn" @click="showConfigModal = true">
            ⚙️ 系统配置
          </button>
        </div>
        
        <InputSection 
          v-model="inputSql"
          @parse="handleParse"
          @load-sample="loadSampleData"
          @direct-execute="handleDirectExecute"
          @generate-er-diagram="handleGenerateErDiagram"
        />
        
        <!-- 直接执行SQL结果区域 -->
        <div v-if="showDirectResult" class="section">
          <h2>🚀 SQL执行结果</h2>
          <QueryResult
            :loading="directQueryLoading"
            :error="directQueryError"
            :result="directQueryResult"
            @close="showDirectResult = false"
          />
        </div>
        
        <div class="section">
          <h2>解析结果</h2>
          
          <!-- 自动执行状态显示 -->
          <div v-if="autoExecuteStatus.message" class="auto-execute-status">
            <div class="status-content">
              <div v-if="autoExecuteStatus.isExecuting" class="spinner-small"></div>
              <span class="status-text">{{ autoExecuteStatus.message }}</span>
            </div>
          </div>
          
          <FilterSection
            v-if="showFilters"
            ref="filterSection"
            :key="tableInfoKey"
            :tables="allTables"
            :table-info="tableInfo"
            :sql-statements="sqlStatements"
            @filter-change="handleFilterChange"
          />
          
          <ResultsSection
            ref="resultsSection"
            :sql-statements="filteredStatements"
            :is-formatted="isFormatted"
            :show-results="showResults"
            @toggle-format="toggleFormat"
          />
        </div>
      </div>
    </div>
    
    <!-- 配置弹窗 -->
    <ConfigModal 
      :visible.sync="showConfigModal"
      @saved="handleConfigSaved"
    />
    
    <!-- ER图弹窗 -->
    <ErDiagramDialog
      :visible="showErDialog"
      :loading="erDiagramLoading"
      :error="erDiagramError"
      :er-result="erDiagramResult"
      @close="showErDialog = false"
    />
  </div>
</template>

<script>
import './assets/styles/global.css'
import HeaderSection from './components/HeaderSection.vue'
import InputSection from './components/InputSection.vue'
import FilterSection from './components/FilterSection.vue'
import ResultsSection from './components/ResultsSection.vue'
import ConfigModal from './components/ConfigModal.vue'
import QueryResult from './components/QueryResult.vue'
import ErDiagramDialog from './components/ErDiagramDialog.vue'
import { parseSQLLog } from './utils/sqlParser'
import { extractTableNames } from './utils/sqlFormatter'
import configManager from './utils/config'
import api from './utils/api'

export default {
  name: 'App',
  components: {
    HeaderSection,
    InputSection,
    FilterSection,
    ResultsSection,
    ConfigModal,
    QueryResult,
    ErDiagramDialog
  },
  data() {
    return {
      inputSql: '',
      showConfigModal: false,
      sqlStatements: [],
      filteredStatements: [],
      allTables: [],
      tableInfo: {}, // 存储表的详细信息
      tableInfoKey: 0, // 用于强制FilterSection重新渲染
      showFilters: false,
      showResults: false,
      isFormatted: true,
      activeFilters: {
        types: {
          select: true,
          insert: true,
          update: true,
          delete: true
        },
        tables: {}
      },
      // 直接执行SQL相关状态
      directQueryResult: null,
      directQueryLoading: false,
      directQueryError: null,
      showDirectResult: false,
      // 自动执行相关状态
      autoExecuteStatus: {
        isExecuting: false,
        total: 0,
        message: ''
      },
      // ER图相关状态
      showErDialog: false,
      erDiagramLoading: false,
      erDiagramError: null,
      erDiagramResult: null
    }
  },
  methods: {
    handleParse() {
      if (!this.inputSql.trim()) {
        alert('请输入SQL日志内容')
        return
      }
      
      try {
        this.sqlStatements = parseSQLLog(this.inputSql)
        this.extractAllTables()
        this.showFilters = true
        this.showResults = true
        this.applyFilters()
        
        // 检查是否需要自动执行查询
        this.checkAutoExecuteQueries()
      } catch (error) {
        alert('解析失败：' + error.message)
      }
    },
    
    extractAllTables() {
      const tables = new Set()
      const tableCounts = {}
      
      // 统计每个表的使用次数
      this.sqlStatements.forEach(stmt => {
        const stmtTables = extractTableNames(stmt.processed)
        stmtTables.forEach(table => {
          tables.add(table)
          tableCounts[table] = (tableCounts[table] || 0) + 1
        })
      })
      
      // 按使用次数排序，次数相同时按字母排序
      this.allTables = Array.from(tables).sort((a, b) => {
        const countA = tableCounts[a] || 0
        const countB = tableCounts[b] || 0
        if (countA !== countB) {
          return countB - countA // 使用次数从高到低
        }
        return a.localeCompare(b) // 字母排序
      })
      
      // 初始化表信息和过滤器
      this.activeFilters.tables = {}
      this.tableInfo = {}
      this.allTables.forEach(table => {
        this.activeFilters.tables[table] = true
        // 使用$set确保新添加的表属性是响应式的
        this.$set(this.tableInfo, table, {
          count: tableCounts[table] || 0,
          comment: '',
          loading: false,
          error: null
        })
      })
      
      console.log('初始化表信息完成:', this.tableInfo)
      console.log('表列表:', this.allTables)
      
      // 更新key强制FilterSection重新渲染
      this.tableInfoKey++
      
      // 异步加载表注释
      this.loadTableComments()
    },
    
    handleFilterChange(filters) {
      this.activeFilters = filters
      this.applyFilters()
    },
    
    applyFilters() {
      this.filteredStatements = this.sqlStatements.filter(stmt => {
        // 检查SQL类型过滤
        const sqlType = this.getSQLType(stmt.processed)
        if (!this.activeFilters.types[sqlType]) {
          return false
        }
        
        // 检查表过滤
        const tables = extractTableNames(stmt.processed)
        if (tables.length === 0) {
          return true // 没有表的语句默认显示
        }
        
        return tables.some(table => this.activeFilters.tables[table])
      })
    },
    
    getSQLType(sql) {
      const upperSQL = sql.toUpperCase().trim()
      if (upperSQL.startsWith('SELECT')) return 'select'
      if (upperSQL.startsWith('INSERT')) return 'insert'
      if (upperSQL.startsWith('UPDATE')) return 'update'
      if (upperSQL.startsWith('DELETE')) return 'delete'
      return 'other'
    },
    
    toggleFormat() {
      this.isFormatted = !this.isFormatted
    },
    
    loadSampleData() {
      this.inputSql = `2025-07-25 20:47:37.091 [qtp1342643327-78] DEBUG c.e.p.e.d.p.d.D.insert - [debug,137] - ==>  Preparing: INSERT INTO dhb_project_performance_construction_wrap ( id, project_id, design_id, ecode, title, remark, etype, task_wrap_type, estimated_price, tenant_code, create_time, create_user, modify_time, modify_user ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2025-07-25 20:47:37.093 [qtp1342643327-78] DEBUG c.e.p.e.d.p.d.D.insert - [debug,137] - ==> Parameters: 313a1d111f4f4b97bb318047bd9d6c60(String), bf4154605f0a6e7689af53140419edca(String), eb0a6b223fd34082a32577f84161b01f(String), A00012(String), 施工放样- PC放样施工0.1.0(String), 111(String), 0(Integer), 008689(String), 0.0(Double), cx_ctl(String), 2025-07-25 20:47:37.09(Timestamp), 355170be-57dc-4ee3-a654-c00e8506afb0(String), 2025-07-25 20:47:37.09(Timestamp), 355170be-57dc-4ee3-a654-c00e8506afb0(String)
2025-07-25 20:51:15.810 [qtp1342643327-62] DEBUG c.e.p.e.s.r.b.B.selectById - [debug,137] - ==>  Preparing: SELECT id,code,name FROM rd_bim WHERE id=?
2025-07-25 20:51:15.810 [qtp1342643327-62] DEBUG c.e.p.e.s.r.b.B.selectById - [debug,137] - ==> Parameters: null`
    },
    
    handleConfigSaved() {
      // 配置保存后的处理
      console.log('配置已保存')
    },
    
    async handleDirectExecute() {
      if (!this.inputSql.trim()) {
        alert('请输入SQL语句')
        return
      }
      
      // 检查数据库配置
      if (!configManager.isDbConfigValid()) {
        alert('请先配置数据库连接信息')
        return
      }
      
      this.showDirectResult = true
      this.directQueryLoading = true
      this.directQueryError = null
      this.directQueryResult = null
      
      try {
        const dbConfig = configManager.getDbConfig()
        const result = await api.executeQuery(this.inputSql.trim(), dbConfig)
        
        if (result.success) {
          this.directQueryResult = result.data
        } else {
          this.directQueryError = result.message || '查询失败'
        }
      } catch (error) {
        this.directQueryError = error.message
      } finally {
        this.directQueryLoading = false
      }
    },
    
    // 检查是否需要自动执行查询
    checkAutoExecuteQueries() {
      const systemConfig = configManager.getSystemConfig()
      if (!systemConfig.autoExecuteSelectAfterParse) {
        return
      }
      
      if (!configManager.isDbConfigValid()) {
        console.log('数据库配置不完整，跳过自动执行')
        return
      }
      
      // 筛选出过滤后的所有SELECT语句
      const selectStatements = this.filteredStatements.filter(stmt => 
        this.getSQLType(stmt.processed) === 'select'
      )
      
      // 调试信息：显示过滤前后的对比
      const totalSqlCount = this.sqlStatements.length
      const filteredSqlCount = this.filteredStatements.length
      const totalSelectCount = this.sqlStatements.filter(stmt => 
        this.getSQLType(stmt.processed) === 'select'
      ).length
      
      console.log('自动执行统计:', {
        总SQL数量: totalSqlCount,
        过滤后SQL数量: filteredSqlCount,
        总SELECT数量: totalSelectCount,
        过滤后SELECT数量: selectStatements.length
      })
      
      if (selectStatements.length === 0) {
        console.log('没有过滤后的SELECT语句，跳过自动执行')
        return
      }
      
      // 延迟100ms开始自动执行，让界面渲染完成
      setTimeout(() => {
        this.autoExecuteSelectQueries(selectStatements)
      }, 100)
    },
    
    // 自动执行所有SELECT语句（并行执行）
    async autoExecuteSelectQueries(selectStatements) {
      this.autoExecuteStatus.isExecuting = true
      this.autoExecuteStatus.total = selectStatements.length
      
      // 获取总的SELECT数量用于对比显示
      const allSelectCount = this.sqlStatements.filter(stmt => 
        this.getSQLType(stmt.processed) === 'select'
      ).length
      
      // 区分显示过滤前后的数量
      if (selectStatements.length === allSelectCount) {
        this.autoExecuteStatus.message = `正在并行执行${selectStatements.length}个SELECT查询...`
      } else {
        this.autoExecuteStatus.message = `正在并行执行${selectStatements.length}个过滤后的SELECT查询（共${allSelectCount}个）...`
      }
      
      // 创建所有查询的Promise数组
      const executePromises = selectStatements.map(async (stmt, i) => {
        // 在过滤后的语句中找到索引（用于界面显示）
        const filteredIndex = this.filteredStatements.findIndex(s => s === stmt)
        
        try {
          // 获取对应的SqlItem组件并触发查询
          const sqlItemRef = this.$refs.resultsSection?.$refs[`sqlItem${filteredIndex}`]?.[0]
          if (sqlItemRef && typeof sqlItemRef.executeQuery === 'function') {
            await sqlItemRef.executeQuery()
            return { success: true, index: filteredIndex }
          } else {
            throw new Error('组件不存在或方法不可用')
          }
        } catch (error) {
          console.error(`自动执行第${i + 1}个过滤后的查询失败:`, error)
          return { success: false, index: filteredIndex, error: error.message }
        }
      })
      
      // 并行执行所有查询
      const results = await Promise.allSettled(executePromises)
      
      // 统计执行结果
      let successCount = 0
      let failedCount = 0
      
      results.forEach((result, index) => {
        if (result.status === 'fulfilled' && result.value.success) {
          successCount++
        } else {
          failedCount++
          if (result.status === 'rejected') {
            console.error(`查询${index + 1}被拒绝:`, result.reason)
          }
        }
      })
      
      this.autoExecuteStatus.isExecuting = false
      
      // 区分显示过滤前后的完成状态
      if (selectStatements.length === allSelectCount) {
        this.autoExecuteStatus.message = `并行执行完成！成功：${successCount}个，失败：${failedCount}个`
      } else {
        this.autoExecuteStatus.message = `过滤后查询执行完成！成功：${successCount}个，失败：${failedCount}个（共${allSelectCount}个SELECT中的${selectStatements.length}个）`
      }
      
      // 3秒后清除状态消息
      setTimeout(() => {
        if (!this.autoExecuteStatus.isExecuting) {
          this.autoExecuteStatus.message = ''
        }
      }, 3000)
    },
    
    // 加载表注释信息
    async loadTableComments() {
      if (this.allTables.length === 0) return
      
      try {
        const dbConfig = configManager.getDbConfig()
        if (!dbConfig || !dbConfig.host) {
          // 如果没有数据库配置，就不加载表注释
          return
        }
        
        // 设置加载状态，使用$set确保响应式更新
        this.allTables.forEach(table => {
          if (this.tableInfo[table]) {
            this.$set(this.tableInfo[table], 'loading', true)
          }
        })
        
        const response = await api.getTableComments(this.allTables, dbConfig)
        
        if (response && response.data) {
          console.log('收到表注释数据:', response.data)
          
          // 更新表注释信息，使用$set确保响应式更新
          Object.keys(response.data).forEach(tableName => {
            if (this.tableInfo[tableName]) {
              console.log(`更新表 ${tableName} 注释:`, response.data[tableName])
              this.$set(this.tableInfo[tableName], 'comment', response.data[tableName] || '')
              this.$set(this.tableInfo[tableName], 'loading', false)
              this.$set(this.tableInfo[tableName], 'error', null)
              console.log(`表 ${tableName} 更新后:`, this.tableInfo[tableName])
            }
          })
          
          console.log('表注释更新完成，触发forceUpdate')
          // 强制更新组件以确保表注释显示
          this.$forceUpdate()
        }
      } catch (error) {
        console.warn('获取表注释失败:', error.message)
        // 设置错误状态，使用$set确保响应式更新
        this.allTables.forEach(table => {
          if (this.tableInfo[table]) {
            this.$set(this.tableInfo[table], 'loading', false)
            this.$set(this.tableInfo[table], 'error', error.message)
          }
        })
        
        // 强制更新组件以确保错误状态显示
        this.$forceUpdate()
      }
    },
    
    // 生成ER图
    async handleGenerateErDiagram() {
      // 检查是否有解析结果
      if (!this.sqlStatements || this.sqlStatements.length === 0) {
        alert('请先解析SQL日志')
        return
      }
      
      // 检查数据库配置
      const dbConfig = configManager.getDbConfig()
      if (!dbConfig || !dbConfig.host) {
        alert('请先配置数据库连接')
        return
      }
      
      this.showErDialog = true
      this.erDiagramLoading = true
      this.erDiagramError = null
      this.erDiagramResult = null
      
      try {
        // 收集数据用于ER图生成
        const erData = await this.collectErDiagramData()
        
        // 调用API生成ER图
        const response = await api.generateErDiagram(erData, dbConfig)
        
        if (response && response.data) {
          this.erDiagramResult = response.data
        } else {
          throw new Error('ER图生成失败')
        }
      } catch (error) {
        console.error('生成ER图失败:', error)
        this.erDiagramError = error.message || '生成ER图失败'
      } finally {
        this.erDiagramLoading = false
      }
    },
    
    // 收集ER图生成所需的数据（只收集通过过滤器选中的数据）
    async collectErDiagramData() {
      const erData = {
        sqlStatements: [],
        queryResults: [],
        tableInfo: {}
      }
      
      // 获取当前过滤器状态
      let activeTypes = ['SELECT', 'INSERT', 'UPDATE', 'DELETE'] // 默认全部
      let activeTables = this.allTables // 默认全部表
      
      if (this.$refs.filterSection) {
        activeTypes = this.$refs.filterSection.getActiveSqlTypes()
        activeTables = this.$refs.filterSection.getActiveTables()
      }
      
      console.log('ER图数据收集 - 激活的SQL类型:', activeTypes)
      console.log('ER图数据收集 - 激活的数据库表:', activeTables)
      
      // 收集过滤后的SQL语句
      this.sqlStatements.forEach(stmt => {
        const sqlType = this.getSQLType(stmt.processed)
        const involvedTables = extractTableNames(stmt.processed)
        
        // 检查SQL类型是否在激活列表中
        if (!activeTypes.includes(sqlType)) {
          return
        }
        
        // 检查是否涉及激活的数据库表
        const hasActiveTable = involvedTables.some(table => activeTables.includes(table))
        if (involvedTables.length > 0 && !hasActiveTable) {
          return
        }
        
        erData.sqlStatements.push({
          sql: stmt.processed,
          type: sqlType,
          tables: involvedTables
        })
      })
      
      // 收集过滤后的查询结果数据
      if (this.$refs.resultsSection) {
        const allQueryResults = this.$refs.resultsSection.getQueryResultsForEr()
        if (allQueryResults) {
          // 应用相同的过滤逻辑
          erData.queryResults = allQueryResults.filter(result => {
            // 检查SQL类型
            if (!activeTypes.includes(result.type)) {
              return false
            }
            
            // 检查涉及的表
            const involvedTables = extractTableNames(result.sql)
            if (involvedTables.length > 0) {
              return involvedTables.some(table => activeTables.includes(table))
            }
            
            return true
          })
        }
      }
      
      // 只收集激活表的信息
      activeTables.forEach(table => {
        if (this.tableInfo[table]) {
          erData.tableInfo[table] = JSON.parse(JSON.stringify(this.tableInfo[table]))
        }
      })
      
      console.log('收集的过滤后ER图数据:', erData)
      console.log(`- SQL语句: ${erData.sqlStatements.length} 条`)
      console.log(`- 查询结果: ${erData.queryResults.length} 个`)
      console.log(`- 表信息: ${Object.keys(erData.tableInfo).length} 个表`)
      
      return erData
    }
  },
  mounted() {
    // 初始化配置
    configManager.init()
    
    // 添加键盘快捷键
    document.addEventListener('keydown', (e) => {
      if (e.ctrlKey && e.key === 'Enter') {
        this.handleParse()
      }
    })
  }
}
</script>

<style>
.container {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.content {
  padding: 40px;
}

.section {
  margin-bottom: 30px;
}

.section h2 {
  color: #374151;
  font-size: 1.5em;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.section h2::before {
  content: "";
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  border-radius: 2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.config-btn {
  background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(107, 114, 128, 0.3);
}

/* 自动执行状态样式 */
.auto-execute-status {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  padding: 12px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2);
}

.status-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.spinner-small {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.status-text {
  font-weight: 500;
}

.status-progress {
  font-size: 12px;
  opacity: 0.9;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .container {
    margin: 10px;
  }
  
  .content {
    padding: 20px;
  }
  
  .status-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>